import router from '@/router'
import { accountLoginRequest, getMenusByRoleId, getUserInfoById } from '@/service/login'
import { IAccount, Menu, UserInfo } from '@/service/login/type'
import cache from '@/utils/cache'
import { mapMenusToRoutes, mapMenusToPermissions } from '@/utils/mapMenus'
import { Module } from 'vuex'
import { IRootState } from '../type'
import { ILoginSate } from './type'

const loginModule: Module<ILoginSate, IRootState> = {
  namespaced: true,
  state() {
    return {
      token: '',
      userInfo: {},
      userMenus: [] as Menu[],
      permissions: []
    }
  },
  getters: {},
  mutations: {
    changeToken(state, token: string) {
      state.token = token
    },
    changeUserInfo(state, userInfo: UserInfo) {
      state.userInfo = userInfo
    },
    changeUserMenus(state, menus: Menu[]) {
      state.userMenus = menus

      // userMenus => routes
      const routes = mapMenusToRoutes(state.userMenus)

      // routes => router.main.children
      routes.forEach((route) => {
        router.addRoute('main', route)
      })

      // 获取用户按钮的权限
      const permissions = mapMenusToPermissions(menus)
      state.permissions = permissions
    }
  },
  actions: {
    async accountLoginAction({ commit, dispatch }, payload: IAccount) {
      const loginResult = await accountLoginRequest(payload)
      const { id, token } = loginResult
      commit('changeToken', token)
      cache.set('token', token)

      // 初始化请求，获取 token 后再发送请求（角色、菜单）
      dispatch('getInitialDataAction', null, { root: true })

      const userInfo = await getUserInfoById(id)
      cache.set('userInfo', userInfo)
      commit('changeUserInfo', userInfo)

      const menus = await getMenusByRoleId(userInfo.role.id)
      cache.set('userMenus', menus)
      commit('changeUserMenus', menus)

      router.push('/main')
    },
    loadLoginState({ commit, dispatch }) {
      const token = cache.get('token')
      if (token) {
        commit('changeToken', token)
        // 初始化请求，获取 token 后再发送请求
        dispatch('getInitialDataAction', null, { root: true })
      }
      const userInfo = cache.get('userInfo')
      if (userInfo) {
        commit('changeUserInfo', userInfo)
      }
      const userMenus = cache.get('userMenus')
      if (userMenus) {
        commit('changeUserMenus', userMenus)
      }
    }
  }
}

export default loginModule
